var packFactory = function() {
	var validator;
	return {
		init : function() {
			//初始化checkBox 初始化行点击选中
			var tableId = "pack_factory_table";
			util.initCheckBox(tableId);
			initSearchSelect();
			//下拉框赋值
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "pkId",
					"value" : $("#serach_packfactoryName").val()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			$('#pack_factory_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "basic/packFactory/getPackFactory.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"/></span></div>';
					},
					"bSortable" : false
				},
				{
					"data" : "packfactoryCode",
					"bSortable" : false,
					"defaultContent": "",
					"render" : function(data, type, full, meta) {
						 return '<a class="showDetail" style="cursor:pointer;color:blue;" data-toggle="modal">'+data+'</a>';
					}
				}, 
				{
					"data" : "packfactoryName",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "province",
					"bSortable" : false,
					"defaultContent": ""
				}
				],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});

			// 查询
			$("#btn_query").click(function(e) {
				var table = $('#pack_factory_table').DataTable();
				table.draw(true);
			});
		    // 重置
			$("#btn_reset").click(function() {
				$("#customer_search_form")[0].reset();
				$(".select2-selection__rendered").empty();
				$(".select2-selection__rendered").append("<span class='select2-selection__placeholder'>请选择</span>");
			});
			//提交表单
			$(function(){
				$("#pack_factory_add_save").click(function(){
					validator = validateMyForm("pack_factory_form");
					if(validator.form()){
						save();
					}else{
						return false;
					}
				})
			})
			
			/*
			 * validate 自定义验证
			 */
			function validateMyForm(formId){
				return $( '#' + formId ).validate({  
					errorElement: 'em',
					errorClass: 'redStar',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	packfactoryCode:'required',
			        	packfactoryName:'required',
			        	zipCode:'checkZipCode'
			            },  
			        messages:{  
			        	packfactoryCode:'不能为空',
			        	packfactoryName:'不能为空',
			        	zipCode:'邮编非法'
			            }, 
			            errorPlacement: function (error, element) { 
			            	//默认以span形式显示在输入框后
		                   error.insertAfter(element);
		                   $(element.next()).attr('title', $(error).text()).tooltip();
		                   $(error).text('');
		                }
			    });
			}
			$.validator.addMethod("checkZipCode",function(value,element,params){  
	            var checkZipCode = /^[0-9][0-9]{5}$/;  
	            return this.optional(element)||(checkZipCode.test(value));  
	        });
			//新增弹窗
			$("#pack_factory_table_add").click(function(){
				$("#pack_factory_add_title").text("新增厂区");
				$("#pkId").val("");
				//初始化省市联动下拉框
				$("#cityDiv").citySelect({  
					   nodata: "none",  
				       required: true,  
				       prov:"北京",  
				       city:"东城区",  
				       dist:""  
				}); 
				$("#add-pack-plant").modal({show:true,keyboard:false});
			})
			
			//保存
			function save(){
				var d = {};
				d['pkId'] = $("#pkId").val();
				d['packfactoryName'] = $("#packfactoryName").val();
				d['packfactoryCode'] = $("#packfactoryCode").val();
				d['province'] = $("#province").find("option:selected").text();
				d['city'] = $("#city").find("option:selected").text();
				d['area'] = $("#area").find("option:selected").text();
				d['zipCode'] = $("#zipCode").val();
				d['address'] = $("#address").val();
				var table = $('#pack_factory_table').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "basic/packFactory/saveOrUpdate.mvc",
					"dataType" : "json",
					"async":false,
					"data" : d,
					"success" : function(resp) {
						if(resp.msg=='SUCCESS'){
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#pack_factory_add_cancel").click();
							initSearchSelect();
							table.draw(true);
						}else if(resp.msg=='DUPLICATE'){
							rmsBox.notify('error', {msg: '编码已经存在！', delay: 3000});
							return;
						} else if(resp.msg=='FAILURE'){
							rmsBox.notify('error', {msg: '保存失败！', delay: 3000});
							return;
						}
						
					}
				});
			};
			
			// 修改
			$('#pack_factory_table_edit').on('click', function(e) {
				var d = [];
				d = util.getCheckedData("pack_factory_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}
				
				$("#pack_factory_add_title").text("编辑厂区");
				var d = [];
				d = getPackFactoryById(util.getCheckedData("pack_factory_table")[0].pkId);
				$('#packfactoryName').val(d.packfactoryName);
				$('#packfactoryCode').val(d.packfactoryCode);
				$("#cityDiv").citySelect({  
					nodata: "none",  
				    required: true,  
				    prov: d.province, //省份 
				    city: d.city, //城市 
				    dist: d.area //区域
				}); 
				
				$('#zipCode').val(d.zipCode);
				$('#address').val(d.address);
				$("#pkId").val(d.pkId);
				$("#add-pack-plant").modal({show:true,keyboard:false});
			});
			//关闭弹窗清空表单内容
			$("#pack_factory_add_cancel").on("click", function(){
				$("#pack_factory_form")[0].reset();
				if (validator) {
					validator.resetForm();
				}
			});
			
			//删除 -----begin
			//删除点击
			$("#pack_factory_table_del").on('click', function(){
				var d = [];
				d = util.getCheckedData("pack_factory_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
				} else {
					util.showModal("#_confirmModal", "您确定要删除选中的记录？", "_confirmModal_yes");
				}
			});
			
			//确认删除
			$("#_confirmModal").on('click', '#_confirmModal_yes', function() {
				var d = [];
				d = util.getCheckedData("pack_factory_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#pack_factory_table').DataTable();
				var selRows = table.rows('.selected');
				$.ajax({
					"type" : "post",
					"url" : "basic/packFactory/delete.mvc",
					"dataType" : "json",
					"async":false,
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						if (resp.msg == 'FAILURE') {
							util.showModal("#_alertModal", "厂区下包含人员不能删除！");
						} else {
							initSearchSelect();
							rmsBox.notify('success', {msg: '删除成功！'});
							selRows.remove();
							table.draw(true);
						}
					}
				});
			});
			//删除 -----end
			
			/*
			 * 获取编辑对象
			 * @param id 主键id
			 */
			function getPackFactoryById(id){
				var data = [];
				$.ajax({
					"type" : "post",
					"url" : "basic/packFactory/getPackFactoryById.mvc",
					"dataType" : "json",
					async: false, 
					"data" : {
						"pkId" : id
					},
					"success" : function(resp) {
						data = resp;
					}
				});
				return　data;
			}
			
			
			//初始化查询下拉框
			function initSearchSelect(){
				util.getOption("main/packfactoryEmploy/getPackFactorys.mvc", null, "serach_packfactoryName");
				//初始化所属客户下拉框
				$("#serach_packfactoryName").select2({
	          	     placeholder:'全部',//默认文字提示
	          	     language: "zh-CN",//汉化
	          	     allowClear: true//允许清空
	          	});
			}
			
			//显示详情
			$("#pack_factory_table").on("click", "a.showDetail",function(e){
				var c = util.getCheckedData("pack_factory_table");
				if (c.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				}
				var d = [];
				d =getPackFactoryById(c[0].pkId);
				console.log(d)
				$("#detail_code").text(d.packfactoryCode);
				$("#detail_name").text(d.packfactoryName); 
				$("#detail_name").attr('title',d.packfactoryName);
				$("#detail_city").text((d.city!=null)?d.city:'');
				$("#detail_province").text((d.province!=null)?d.province:'');
				$("#detail_address").text((d.address!=null)?d.address:'');
				$("#detail_address").attr('title',d.address);
				$("#detail_zipCode").text((d.zipCode!=null)?d.zipCode:'');
				$("#addID-detail").modal({show:true,keyboard:false});
			});
			
		}
	};
}();
